<!--公告通知-->
<template>
  <div id="noticeCreate" class="app-container">
    <!--新增/编辑侧边栏-->
    <el-form
      ref="dataForm"
      class="flex-main"
      style="overflow: auto;"
      :rules="contentRules"
      :model="contentRecord"
      label-width="100px"
      label-position="right">
      <DocEditor
        :form="{
          title:contentRecord.title,
          contnetAbstract:contentRecord.summary,
          content:contentRecord.content
        }"
        :catalog="constants.FILE_CATALOG_NEWS"
        :error="errorMsg"
        :show-input="['abstract']"
        @result="handleEditorResult">
        <template>
          <el-form-item label="作者:" prop="author">
            <el-input v-model="contentRecord.author" maxlength="10" show-word-limit placeholder="请输入文章作者" clearable />
          </el-form-item>
          <el-form-item label="所属栏目:" prop="categoryIds">
            <categoryCascader v-model="contentRecord.categoryIds" />
          </el-form-item>
          <el-form-item label="关键字:" prop="keywords">
            <el-input
              v-model="contentRecord.keywords"
              :rows="3"
              type="textarea"
              maxlength="200"
              show-word-limit
              clearable
              placeholder="请输入关键字(限200字以内)" />
          </el-form-item>
          <el-form-item label="meta描述:" prop="metaDescription">
            <el-input
              v-model="contentRecord.metaDescription"
              :rows="5"
              type="textarea"
              maxlength="450"
              show-word-limit
              clearable
              placeholder="请输入描述(限450字以内)" />
          </el-form-item>
          <el-form-item label="原创:">
            <el-switch
              v-model="contentRecord.isOriginal"
              active-color="#4a5dff"
              :active-value="1"
              :inactive-value="0" />
          </el-form-item>
          <template v-if="contentRecord.isOriginal===0">
            <el-form-item label="来源:" prop="source">
              <el-input v-model="contentRecord.source" maxlength="50" show-word-limit placeholder="请输入文章来源" clearable />
            </el-form-item>
            <el-form-item label="链接:" prop="sourceUrl">
              <el-input v-model="contentRecord.sourceUrl" maxlength="100" show-word-limit placeholder="请输入文章来源链接" clearable>
                <el-button slot="append" icon="el-icon-search" @click="handleGoSourceUrl" />
              </el-input>
            </el-form-item>
          </template>
        </template>
        <template slot="bottom">
          <el-form-item label="封面:" prop="image">
            <MultipleImageUpload v-model="contentRecord.images" :limit="3" :crop-ratio="2 / 1" :catalog="constants.FILE_CATALOG_NEWS" :width="92" />
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="收藏次数:" prop="collections">
                <el-input v-model="contentRecord.collections" oninput="value=value.replace(/\D/g, '')" show-word-limit placeholder="请输入初次收藏次数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="浏览总数:" prop="views">
                <el-input v-model="contentRecord.views" oninput="value=value.replace(/\D/g, '')" show-word-limit placeholder="请输入初次浏览总数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="点赞次数:" prop="thumbUpNum">
                <el-input v-model="contentRecord.thumbUpNum" oninput="value=value.replace(/\D/g, '')" show-word-limit placeholder="请输入初次点赞次数" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="置顶:">
            <el-switch
              v-model="contentRecord.isTop"
              active-color="#4a5dff"
              :active-value="1"
              :inactive-value="0" />
          </el-form-item>
          <el-form-item label="允许评论:">
            <el-switch
              v-model="contentRecord.isAllowComment"
              active-color="#4a5dff"
              :active-value="1"
              :inactive-value="0" />
          </el-form-item>
          <el-form-item label="附件:">
            <SimpleUploader v-model="contentRecord.files" :catalog="constants.FILE_CATALOG_NEWS" />
          </el-form-item>
        </template>
        <template slot="footer">
          <el-button type="default" plain @click="status==='create'?createData(0):updateData(0)">暂存 </el-button>
          <el-button type="primary" plain @click="status==='create'?createData(1):updateData(1)">仅保存 </el-button>
          <el-button plain @click="handleGoBack">返回</el-button>
        </template>
        <template slot="desc">
          向下滑动鼠标，还有内容哟！
        </template>
      </DocEditor>

    </el-form>
  </div>
</template>

<script>
import categoryCascader from './categoryCascader'
export default {
  components: { categoryCascader },

  data() {
    return {
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now()
        }
      },
      loading: null,
      status: 'create',
      errorMsg: null,
      contentRecord: {
        isSelf: '0'
      },
      contentRules: {
        categoryIds: [
          { required: true, message: '请选择所属栏目', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入责任编辑', trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: '请输入keyword关键字', trigger: 'blur' }
        ],

        views: [
          { required: true, message: '请输入浏览总数', trigger: 'blur' }
        ],
        thumbUpNum: [
          { required: true, message: '请输入点赞次数', trigger: 'blur' }
        ],
        collections: [
          { required: true, message: '请输入收藏次数', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入正文', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    $route: function(val) {
      this.init()
    }
  },
  created() {
    this.init()
  },
  destroyed() {
  },
  methods: {
    init() {
      var id = this.$route.query.id
      if (id) {
        this.loading = this.$loading({
          lock: true,
          text: '正在加载数据...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        setTimeout(() => {
          this.handleUpdate(id)
        }, 1000)
      } else {
        this.handleCreate()
      }
    },
    handleEditorResult(val) {
      this.contentRecord = {
        ...this.contentRecord,
        title: val.title,
        summary: val.contnetAbstract,
        content: val.content
      }
    },
    handleGoBack() {
      this.$router.push({ path: '/content' })
      const view = this.$route
      delete view.icon
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {})
    },
    /* 新增*/
    handleCreate() {
      this.contentRecord = {
        files: [],
        title: '',
        collections: 0,
        views: 0,
        thumbUpNum: 0,
        isAllowComment: 1,
        images: '',
        categoryIds: [],
        isOriginal: 1

      }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(status) {
      if (!this.T.removeHtmltag(this.contentRecord.title)) {
        this.errorMsg = '请填写标题'
        return true
      }
      if (!this.T.removeHtmltag(this.contentRecord.content)) {
        this.errorMsg = '请填写正文内容'
        return true
      }
      var temp = Object.assign({}, this.contentRecord)
      var images = []
      if (temp.images) {
        images = temp.images.split(',')
      }
      for (var i = 0; i < images.length; i++) {
        temp['image' + (i + 1)] = images[i]
      }
      if (this.contentRecord.isOriginal === 1) {
        this.contentRecord = {
          ...this.contentRecord,
          source: '',
          sourceUrl: ''
        }
      }
      temp = {
        ...temp,
        status: status,
        file: temp.files.join(','),
        categoryId: temp.categoryIds ? temp.categoryIds[temp.categoryIds.length - 1] : ''
      }
      delete temp.files
      delete temp.images
      delete temp.categoryIds
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('contentArticleSave', temp).then(response => {
            if (status === 0) {
              this.$modal.msgSuccess('暂存成功')
              this.$router.push({ name: 'contentCreate', query: { id: response.id }})
            } else {
              this.$confirm('创建成功', '提示', {
                confirmButtonText: '继续添加',
                cancelButtonText: '文章列表',
                type: 'warning'
              }).then(() => {
                this.$router.push({ name: 'contentCreate', query: { }})
                this.init()
              }).catch(() => {
                this.handleGoBack()
              })
            }
          }).catch(() => {
          })
        }
      })
    },

    /* 编辑*/
    async handleUpdate(id) {
      var contentRes = await this.$store.dispatch('contentArticleGetDetailsById', id)
      if (this.loading) {
        this.loading.close()
      }
      this.contentRecord = contentRes // copy obj
      var images = []
      if (this.contentRecord.image1) {
        images.push(this.contentRecord.image1)
      }
      if (this.contentRecord.image2) {
        images.push(this.contentRecord.image2)
      }
      if (this.contentRecord.image3) {
        images.push(this.contentRecord.image3)
      }
      this.contentRecord = {
        ... this.contentRecord,
        files: this.contentRecord.file ? this.contentRecord.file.split(',') : [],
        categoryIds: contentRes._fullCategoryIds,
        images: images.join(',')
      }
      this.status = 'update'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData(status) {
      if (!this.T.removeHtmltag(this.contentRecord.title)) {
        this.errorMsg = '请填写标题'
        return true
      }
      if (!this.T.removeHtmltag(this.contentRecord.content)) {
        this.errorMsg = '请填写正文内容'
        return true
      }
      if (this.contentRecord.isOriginal === 1) {
        this.contentRecord = {
          ...this.contentRecord,
          source: '',
          sourceUrl: ''
        }
      }
      var temp = Object.assign({}, this.contentRecord)
      var images = []
      if (temp.images) {
        images = temp.images.split(',')
      }
      for (var i = 0; i < 3; i++) {
        temp['image' + (i + 1)] = ''
      }
      for (var j = 0; j < images.length; j++) {
        temp['image' + (j + 1)] = images[j]
      }
      temp = {
        ...temp,
        file: temp.files.join(','),
        categoryId: temp.categoryIds ? temp.categoryIds[temp.categoryIds.length - 1] : ''
      }
      if (status === 1) {
        temp.status = 1
      }
      delete temp.files
      delete temp.images
      delete temp.categoryIds
      delete temp._fullCategoryIds
      delete temp._fullCategoryNames
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('contentArticleUpdate', temp).then(response => {
            if (status === 0) {
              this.$modal.msgSuccess('暂存成功')
            } else {
              this.$confirm('修改成功', '提示', {
                confirmButtonText: '继续添加',
                cancelButtonText: '文章列表',
                type: 'warning'
              }).then(() => {
                this.$router.push({ name: 'contentCreate', query: { }})
              }).catch(() => {
                this.handleGoBack()
              })
            }
          }).catch(() => {
          })
        }
      })
    },
    handleGoSourceUrl() {
      if (!this.contentRecord.sourceUrl) {
        return
      }
      window.open(this.contentRecord.sourceUrl, '_blank')
    }
  }
}
</script>
  <style lang="scss">
  #noticeCreate{
    background-color: #fff;
  }
  </style>

